package org.jrfe.sys;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class StateManager {

	private static StateManager mgr;
	
	private Map<String, State> stateMap;
	private State activeState;
	
	private StateManager() {
		stateMap = new HashMap<String, State>();
	}

	public void addState(State state){
		stateMap.put(state.getStateName(), state);
	}
	
	public void removeState(State state){
		stateMap.remove(state.getStateName());
	}
	
	public State getState(String stateName){
		return stateMap.get(stateName);
	}
	
	public void setActiveState(String stateName){
		State s = stateMap.get(stateName);
		if(s == null){
			throw new NullPointerException("State with name:"+stateName+" Not found");
		}
		changeState(s);
	}
	
	public void setActiveState(State state){
		if(stateMap.containsKey(state.getStateName())){
			changeState(state);
		}else{
			addState(state);
			changeState(state);
		}
	}
	
	private void changeState(State state){
		if(activeState != null){
			activeState.close();
		}
		
		activeState = state;
		if(!activeState.isInitialized()){
			activeState.init();
		}
		
		activeState.open();	
	}
	
	public void destroy(){
		for(Entry<String, State> e : stateMap.entrySet()){
			e.getValue().close();
			e.getValue().destroy();
		}
		
		stateMap.clear();
	}
	
	
	public State getActiveState() {
		return activeState;
	}
	
	
	public synchronized static StateManager getInstance(){
		if(mgr == null){
			mgr = new StateManager();
		}
		return mgr;
	}
	
	public synchronized static void destoryManager(){
		if(mgr != null){
			mgr.destroy();
			mgr = null;
		}
	}
	
}
